package com.tianlu.store.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Objects;

/**
 * @author liangdl
 * @since 2023/4/22 14:48
 */
@Slf4j
public class WxUtils {
    private static final String APP_ID = "wxe206d8886bb645fd";
    private static final String APP_SECRET = "f28dd18db0a2a02d9b23b901ffa4777b";

    public static String getAccessToken() {
        Object redisToken = RedisTemplateUtils.get("access_token_" + APP_ID);
        if (Objects.nonNull(redisToken)) {
            return (String) redisToken;
        }

        String url = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", APP_ID, APP_SECRET);
        String body = HttpRequest.get(url).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(body);
        if (Objects.isNull(jsonObject) || StrUtil.isBlank(jsonObject.getString("access_token"))) {
            return "";
        }

        RedisTemplateUtils.set("access_token_" + APP_ID, jsonObject.getString("access_token"), 7000);
        return jsonObject.getString("access_token");
    }

    public static String getOpenId(String code) {
        String url = MessageFormat.format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", APP_ID, APP_SECRET, code);
        String body = HttpRequest.get(url).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(body);
        log.info("openid请求结果：" + jsonObject);
        if (Objects.isNull(jsonObject) || StrUtil.isBlank(jsonObject.getString("openid"))) {
            return "";
        }
        return jsonObject.getString("openid");
    }

    public static String getPhoneNumber(String code) {
        String accessToken = getAccessToken();
        String url = MessageFormat.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}", accessToken);
        JSONObject json = new JSONObject();
        //搜索关键字
        json.put("code", code);
        String body = HttpRequest.post(url).body(String.valueOf(json)).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (Objects.isNull(jsonObject) || Objects.isNull(jsonObject.getJSONObject("phone_info"))) {
            return "";
        }
        return jsonObject.getJSONObject("phone_info").getString("phoneNumber");
    }

    public static String getUnlimitedQRCode(Long userId) {
        String accessToken = getAccessToken();
        String url = MessageFormat.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", accessToken);
        JSONObject json = new JSONObject();
        //搜索关键字
        json.put("page", "pages/home/home");
        json.put("scene", "parentId=" + userId);
        json.put("check_path", false);
        json.put("env_version", "trial");
//        json.put("env_version", "release");
        HttpResponse response = HttpRequest.post(url).body(String.valueOf(json)).execute();
        if (response.getStatus() == HttpStatus.OK.value()) {
            InputStream inputStream = response.bodyStream();
            return CosFileUtils.uploadQRCode(inputStream, userId + ".jpg");
        }
        return "";
    }

}
